package flyshoes.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import flyshoes.mybatis.entity.Order;
import flyshoes.mybatis.enums.OrderStatus;
import flyshoes.mybatis.service.serviceImpl.OrderServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@Controller
@RequiredArgsConstructor
@RequestMapping("/pay")
public class PayServiceController {

    @Value("${app.id}")
    private String appid;
    @Value("${app.privatekey}")
    private String privateKey;
    @Value("${app.publickey}")
    private String publicKey;
    @Value("${notify.url}")
    private String notifyUrl;
    @Value("${return.url}")
    private String returnUrl;
    @Value("${sign.type}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${pay.gateway}")
    private String payGateWay;

    private final OrderServiceImpl orderService;



    @GetMapping("/payPage")//这个给前端去调用  这个方式ajax调用不方便处理，最好是窗口加载
    public void returnHtmlPage( String orderNumber, HttpServletResponse response) {
        //orderNumber = "FS83a160a7-f265-45b4-80e8-6d6a0cc11445";
        List<Order> list = orderService.lambdaQuery().eq(Order::getOrderNumber,orderNumber).list();
        if (list.isEmpty()){
            System.out.println("未找到订单");
        }
        Order order = list.get(0);
        //orderNumber = "FS83a160a7-f265-45b4-80e8-6d6a0cc11445";
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new
                DefaultAlipayClient(payGateWay, appid, privateKey, "json", charset, publicKey, signType);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //同步回调，如果本地调度只会走同步，这里的界面就是你付款后跳转的界面
        alipayRequest.setReturnUrl(returnUrl);

//异步回调，外网要能访问
        alipayRequest.setNotifyUrl(notifyUrl);
//订单名称，必填
        String subject = "飞跃鞋城付款" + orderNumber;
//商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = orderNumber;
//付款金额，必填
        String total_amount = order.getTotalPrice() + "";
//商品描述，可空
        String body = "鞋";
// 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-
        // 天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如
        //  1.5h，可转换为 90m。
        String timeout_express = "1c";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no +
                "\"," + "\"total_amount\":\"" + total_amount + "\"," + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"timeout_express\":\"" + timeout_express + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String form = "";

        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生 成表单
            response.setContentType("text/html;charset=" + charset);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //这个就是支付完成后，支付宝会跳转的我们本地的地址,这个从payPage这个页面地址开始一直在一个窗口中
    @GetMapping("/returnPage")
    public String returnUrl(String out_trade_no){
        System.out.println("=========支付宝同步回调========");
        //改订单状态为已支付
//        UpdateWrapper<TOrders> uw = new UpdateWrapper<>();
//        uw.set("status",2);
//        uw.eq("id",Integer.parseInt(out_trade_no));
//        service.update(uw);
        orderService.lambdaUpdate().eq(Order::getOrderNumber,out_trade_no)
                .set(Order::getOrderStatus, OrderStatus.ALREADYPAY)
                .update();
        return "forward:payFinish.html";//支付成功完成后的页面
    }

    @PostMapping("/notifyCallback")  // 注意这里必须是POST接口
    public String payNotify(Map<String, String> params) throws Exception {
        if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            System.out.println("=========支付宝异步回调========");
            String tradeNo = params.get("out_trade_no");
            // String gmtPayment = params.get("gmt_payment");
            // String alipayTradeNo = params.get("trade_no");
           /* System.out.println("交易名称: " + params.get("subject"));
            System.out.println("交易状态: " + params.get("trade_status"));
            System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
            System.out.println("商户订单号: " + params.get("out_trade_no"));
            System.out.println("交易金额: " + params.get("total_amount"));
            System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
            System.out.println("买家付款时间: " + params.get("gmt_payment"));
            System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));*/
//            UpdateWrapper<TOrders> uw = new UpdateWrapper<>();
//            uw.set("status",2);
//            uw.eq("id",Integer.parseInt(tradeNo));
//            service.update(uw);
            orderService.lambdaUpdate().eq(Order::getOrderNumber,tradeNo)
                    .set(Order::getOrderStatus, OrderStatus.ALREADYPAY)
                    .update();
            //更新订单状态
        }
        return "success";
    }
}
